package cn.tedu.tmall.front.mall.dao.persist.search.impl;

import cn.tedu.tmall.common.pojo.po.GoodsSearchPO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.front.mall.dao.persist.search.IGoodsSearchRepository;
import cn.tedu.tmall.front.mall.pojo.vo.GoodsSearchVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class GoodsSearchRepositoryImpl implements IGoodsSearchRepository {
    @Autowired
    private GoodsElasticSearchRepository searchRepository;
    @Override
    public PageData<GoodsSearchVO> customSearch(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(--pageNum,pageSize);
        SearchPage<GoodsSearchPO> searchPage = searchRepository.customSearchPage(keyword, pageable);
        PageData<GoodsSearchVO> pageData = convertSearchPageToPageData(searchPage);
        return pageData;
    }

    private PageData<GoodsSearchVO> convertSearchPageToPageData(SearchPage<GoodsSearchPO> searchPage){
        SearchHits<GoodsSearchPO> searchHits = searchPage.getSearchHits();
        List<GoodsSearchVO> list = new ArrayList<>();
        for (SearchHit<GoodsSearchPO> searchHit : searchHits) {
            GoodsSearchVO goodsSearchVO = convertSearchHitToVo(searchHit);
            list.add(goodsSearchVO);
        }
        PageData<GoodsSearchVO> pageData = new PageData<>();
        pageData.setMaxPage(searchPage.getTotalPages());
        pageData.setCurrentPage(searchPage.getNumber());
        pageData.setPageSize(searchPage.getSize());
        pageData.setTotal(searchHits.getTotalHits());
        pageData.setList(list);
        return pageData;
    }

    private GoodsSearchVO convertSearchHitToVo(SearchHit<GoodsSearchPO> searchHit){
        GoodsSearchPO goodsSearchPO = searchHit.getContent();
        List<String> title = searchHit.getHighlightField("title");
        GoodsSearchVO goodsSearchVO = new GoodsSearchVO();
        BeanUtils.copyProperties(goodsSearchPO,goodsSearchVO);
        if(title.size()>0){
            goodsSearchVO.setTitle(title.get(0));
        }
        return goodsSearchVO;
    }
}
